package com.cw.jeeyt.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * SpringSecurity配置
 *
 * @author: chenw
 * @create: 2018-11-07 21:22
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private AuthenticationProvider provider;
    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailHander;
    @Value("${nginx.path}")
    private String nginxPath;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
            .loginPage(nginxPath + "/login/to-login")
            .loginProcessingUrl("/login/userLogin")
            .successForwardUrl("/system/index")
            .successHandler(myAuthenticationSuccessHandler)
            .failureHandler(myAuthenticationFailHander)
            .permitAll()  //表单登录，permitAll()表示这个不需要验证 登录页面，登录失败页面
            .and()
            .rememberMe()
            .rememberMeParameter("remember-me")
            .userDetailsService(userDetailsService)
            .tokenRepository(persistentTokenRepository())
            .tokenValiditySeconds(6000)
            .and()
            .authorizeRequests()
            .antMatchers("/api/**", "/login/**", "/public/index", "/captcha/**", "/css/**", "/fonts/**", "/images/**",
                "/js/**", "/plugins/**","/**/*.css","/**/*.js")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .headers()
            .frameOptions()
            .disable()
            .and()
            .logout()
            .logoutSuccessUrl("/login/to-login")
            .and()
            .csrf()
            .disable();
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers("/static/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(provider);
        /*auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("123456")).roles("USER")
                .and().withUser("test").password(passwordEncoder().encode("test123")).roles("ADMIN");*/
    }

    /**
     * 记住我功能的token存取器配置
     *
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }
}
